<?php
namespace app\member\controller;
class Mobile extends Common{
	function __construct(){
	    parent::__construct();
	    $this->assign('_nav',json_encode(config("navs.1.children"),JSON_UNESCAPED_UNICODE));
	}
    function index(){
        $where=['member_id'=>$this->user['id']];
        $options=[
            'order'=>'s_time desc',
            'group'=>'s_time',
            'field'=>'count(id) as counts,sum(status=0) as notReads,sum(status=3) as waits,sum(status=1) as weixins,sum(status=2) as notWeixins,s_time'
        ];
        $list=model($this->table)->readAll($where,true,$options);
        $this->assign('list',$list);
        return view();
    }
	// 手机号码列表
    function detail($val='',$type='-1',$s_time=0){
    	$params=[
    	    'val'=>$val,
    	    'type'=>$type,
    	];
    	$where=['member_id'=>$this->user['id']];
    	if(strlen($val)){
    		$where['tel']=['tel','like',"%$val%"];
    	}
    	if($type>=0){
    		$where['status']=$type;
    	}
        if($s_time>=0){
            $where['s_time']=$s_time;
        }
    	$list=model($this->table)->readAll($where,true,['order'=>'status']);
        $list->appends($params);
    	$this->assign('list',$list);
    	$this->assign('params',$params);
    	return view();
    }
    /**
     * 导出微信号到csv文件(Excel)
     * @param  integer $s_time 导入时间（批次）
     * @return json
     */
    function exports($s_time=0){
        $s_times=input('s_times/a',[]); // 多项删除
        if($s_time<=0&&empty($s_times)){
            $this->error(lang('Data does not exist'));
        }
        $member_id=$this->user['id'];
        $where=[
            'status'=>1,
            's_time'=>$s_time,
            'member_id'=>$member_id
        ];
        if(!empty($ids)){
            $where=[
                'member_id'=>$member_id,
                's_time'=>['s_time','in',$s_times]
            ];
        }
        $list=model($this->table)->readAll($where,0,['field'=>'weixin,tel,nickname,s_time'])->toArray();
        $s_time=0;
        foreach ($list as $k => $v) {
            $list[$k]=[
                $v['weixin']."\t",
                $v['tel']."\t",
                $v['nickname']."\t"
            ];
            if($s_time===0){
                $s_time=$v['s_time'];
            }
        }
        $filename='微信号列表-';
        if($s_time>0){
           $filename.=date('YmdHis',$s_time).'-'; 
        }
        $filename.=date('Y-m-d').'.csv';
        exportToExcel($filename, $list,["微信号\t","手机号码\t","微信昵称\t"]);
            
        // if($del){
        //     $this->success(lang('Successful operation'));
        //     die;
        // }
        // $this->error(lang('Failed operation'));
    }
    /**
     * 还原功能（供测试使用，减少初始数据的导入量）
     * @return [type] [description]
     */
    function back(){
        model($this->table)->edit(['status'=>0],['id'=>['id','>',0]]);
        $this->success('操作成功');
    }
    /**
     * 查询是否微信号(已废弃，参考Task/newTask)
     * @param  array   $checkDevs 选择的设备ID？
     * @param  integer $nums      本次查询数量
     * @return json
     */
    function queryWeixin($checkDevs=[],$nums=1){
    	$user=$this->user;
    	if(empty($checkDevs)){
    		$devs=model('device')->readAll(['member_id'=>$user['id']],0,['field'=>'id']);
    		foreach($devs as $v) {
    			array_push($checkDevs,$v['id']);
    		}
    		if(!count($devs)){
    			$this->error('请先添加设备');
    		}
    	}
    	$mobileModel=model('mobile');
    	$number=$mobileModel->where(['member_id'=>$user['id'],'status'=>0])->order('id')->limit(0,$nums)->field('id,tel')->select();
    	if(!count($number)){
    		$this->error('不存在未查询的手机号');
    	}
    	$queryIds=[];
    	foreach($number as $k => $v) {
    		$number[$k]=$v['tel'];
    		array_push($queryIds,['id'=>$v['id'],'status'=>3]);
    	}

    	$time=time();
    	$data=[
    		'member_id'=>$user['id'],
    		'title'=>'查询手机号是否微信号',
    		'msg'=>'',
    		'interval'=>0,
    		'event'=>'extraTask',
    		'dev'=>[],
    		's_time'=>$time,
    		'type'=>1,
    		'action'=>1,
    		'loop'=>0, // 是否循环请求
    		'start_time'=>$time,
    		'status'=>1,
    		'remark'=>'(扩展任务)查询手机号是否微信号',
    		'options'=>[
                'friends'=>0, // 发送好友
                'group'=>0, // 发送群组
                'interval'=>0, // 发送间隔
                'sex'=>2, // 性别筛选 0：女 1：男 2：所有
                'number'=>[], // 微信号、QQ号、手机号
                'count'=>0, // 操作数量限制0表示不限制 例：同意好友添加请求 10 个
                'limit'=>100, // 默认设置:100 例：点赞 100 个
                'sign'=>[], // 个性签名(一个数组 多行随机抽取)
                'msg'=>[], // 加好友时的打招呼信息(一个数组 多行随机抽取)
            ]
    	];

    	foreach($checkDevs as $key => $v) {
    		$data['dev']=[$v];
    		$data['options']['number']=$number;
    		$rs=$this->createTask($data,$user['id']); // 创建任务
    		if($rs['success']){
    			// 更新已加入查询队列的列
    		    $mobileModel->edit($queryIds);
    		}
    		// 如果存在未查询的手机则继续创建查询任务
    		$number=$mobileModel->where(['member_id'=>$user['id'],'status'=>0])->order('id')->limit(0,$nums)->field('id,tel')->select();
    		if(!count($number)){
    			break;
    		}
    		$queryIds=[];
    		foreach($number as $k => $v) {
    			$number[$k]=$v['tel'];
    			array_push($queryIds,['id'=>$v['id'],'status'=>3]);
    		}
    	}
    	$this->success(lang('Create success'));
    }
    // 批量导入
    function addAll($data=[]){
    	if(request()->isAjax()||request()->isPost()){
    		if(empty($data)){
    			$this->error('导入数据不能为空');
    		}
    		$time=time();
    		$member_id=$this->user['id'];
    		foreach ($data as $k => $v) {
    			$data[$k]=[
    				'member_id'=>$member_id,
    				'tel'=>$v[0],
    				's_time'=>$time,
    			];
    		}
    		$add=model($this->table)->add($data);
    		if($add){
    			$this->success('导入成功!');
    			die;
    		}
    		$this->error('系统繁忙、导入失败');
    	}
    }
    /**
     * 分批次删除
     * @param  integer $s_time     导入时间（按该时间分组）
     * @param  integer $notWeixins 删除类型（0 删除所有 1：删除该批次的非微信号）
     * @return json
     */
    function delRows($s_time=0,$notWeixins=0){
        if(request()->isAjax()||request()->isPost()){
            $s_times=input('s_times/a',[]); // 多项删除
            if($s_time<=0&&empty($s_times)){
                $this->error(lang('Data does not exist'));
            }
            $member_id=$this->user['id'];
            $where=['s_time'=>$s_time,'member_id'=>$member_id];
            if(!empty($ids)){
                $where=[
                    'member_id'=>$member_id,
                    's_time'=>['s_time','in',$s_times]
                ];
            }
            if($notWeixins>0){
                $where['status']=2;
            }
            $del=model($this->table)->del($where);
            if($del){
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
}
